from time import time

class NZB:
	def __init__(self, poster, groups, date = 0):
		if date == 0:
			date = int(time())
		self.poster = poster
		self.groups = groups
		self.date = date
		self.files = []
		self.current_file = []
		self.current_subject = ''

	def __str__(self):
		result = []
		result.append('''<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.0//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd">
<nzb xmlns="http://www.newzbin.com/DTD/2003/nzb">
''')
		for i in self.files:
			result.append('	<file poster="%s" date="%d" subject="%s">\n		<groups>\n' % (self.poster, self.date, i[0]))
			for j in self.groups:
				result.append('			<group>%s</group>\n' % j)
			result.append('		</groups>\n		<segments>\n')
			for j in i[1]:
				result.append('			<segment bytes="%d" number="%d">%s</segment>\n' % (j[0], j[1], j[2]))
			result.append('		</segments>\n	</file>\n')
		result.append('</nzb>\n')
		return ''.join(result)
		
	def add_file(self, subject):
		self.current_file = []
		self.current_subject = subject.replace('"', '&quot;')
	
	def finished_file(self):
		self.files.append((self.current_subject, self.current_file))
	
	def add_segment(self, bytes, number, mid):
		self.current_file.append((bytes, number, mid))